package net.begincode.maiev.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import net.begincode.maiev.annotation.NeedLogin;
import net.begincode.maiev.model.MaievUser;

public class NeedLoginInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
			// 没有声明需要权限,或者声明不验证权限
			if (needLogin == null || needLogin.need() == false) {
				return true;
			} else {
				MaievUser user = (MaievUser) request.getSession().getAttribute("loginUser");
				if (user != null)
					return true;
				else {
					// 如果验证失败, 返回到登录界面
					response.sendRedirect(request.getContextPath() + "/user/login.htm");
					return false;
				}
			}
		} else {
			return true;
		}
	}
}
